{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "模型训练好之后，我们就要想办法将其持久化保存下来，不然关机或者程序退出后模型就不复存在了。本文介绍两种持久化保存模型的方法："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在介绍这两种方法之前，我们得先创建并训练好一个模型，还是以mnist手写数字识别数据集训练模型为例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow import keras\n",
    "from tensorflow.keras import layers, optimizers, Sequential"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train on 60000 samples\n",
      "60000/60000 [==============================] - 3s 46us/sample - loss: 2.3700\n"
     ]
    }
   ],
   "source": [
    "model = Sequential([  # 创建模型\n",
    "    layers.Dense(256, activation=tf.nn.relu),\n",
    "    layers.Dense(128, activation=tf.nn.relu),\n",
    "    layers.Dense(64, activation=tf.nn.relu),\n",
    "    layers.Dense(32, activation=tf.nn.relu),\n",
    "    layers.Dense(10)\n",
    "    ]\n",
    ")\n",
    "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n",
    "x_train = x_train.reshape(60000, 784).astype('float32') / 255\n",
    "x_test = x_test.reshape(10000, 784).astype('float32') / 255\n",
    "\n",
    "model.compile(loss='sparse_categorical_crossentropy',\n",
    "              optimizer=keras.optimizers.RMSprop())\n",
    "history = model.fit(x_train, y_train,  # 进行简单的1次迭代训练\n",
    "                    batch_size=64,\n",
    "                    epochs=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 方法一：model.save()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "通过模型自带的save()方法可以将模型保存到一个指定文件中，保存的内容包括：\n",
    "- 模型的结构\n",
    "- 模型的权重参数\n",
    "- 通过compile()方法配置的模型训练参数\n",
    "- 优化器及其状态"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.save('mymodels/mnist.h5')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用save()方法保存后，在mymodels目录下就会有一个mnist.h5文件。需要使用模型时，通过keras.models.load_model()方法从文件中再次加载即可。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:Sequential models without an `input_shape` passed to the first layer cannot reload their optimizer state. As a result, your model isstarting with a freshly initialized optimizer.\n"
     ]
    }
   ],
   "source": [
    "new_model = keras.models.load_model('mymodels/mnist.h5')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "新加载出来的new_model在结构、功能、参数各方面与model是一样的。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "通过save()方法，也可以将模型保存为SavedModel 格式。SavedModel格式是TensorFlow所特有的一种序列化文件格式，其他编程语言实现的TensorFlow中同样支持："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/chb/anaconda3/envs/study_python/lib/python3.7/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1781: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "If using Keras pass *_constraint arguments to layers.\n",
      "INFO:tensorflow:Assets written to: mymodels/mnist_model/assets\n"
     ]
    }
   ],
   "source": [
    "model.save('mymodels/mnist_model', save_format='tf')  # 将模型保存为SaveModel格式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "new_model = keras.models.load_model('mymodels/mnist_model')  # 加载模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__path__', '__file__', '__cached__', '__builtins__', '_sys', 'Sequential', 'Model', 'clone_model', 'model_from_config', 'model_from_json', 'model_from_yaml', 'load_model', 'save_model']\n"
     ]
    }
   ],
   "source": [
    "print(keras.models.__dir__())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 方法二：model.save_weights()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "save()方法会保留模型的所有信息，但有时候，我们仅对部分信息感兴趣，例如仅对模型的权重参数感兴趣，那么就可以通过save_weights()方法进行保存。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.save_weights('mymodels/mnits_weights')  # 保存模型权重信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tensorflow.python.training.tracking.util.CheckpointLoadStatus at 0x7f49c42b87d0>"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "new_model = Sequential([  # 创建新的模型\n",
    "    layers.Dense(256, activation=tf.nn.relu),\n",
    "    layers.Dense(128, activation=tf.nn.relu),\n",
    "    layers.Dense(64, activation=tf.nn.relu),\n",
    "    layers.Dense(32, activation=tf.nn.relu),\n",
    "    layers.Dense(10)\n",
    "    ]\n",
    ")\n",
    "new_model.compile(loss='sparse_categorical_crossentropy',\n",
    "              optimizer=keras.optimizers.RMSprop())\n",
    "new_model.load_weights('mymodels/mnits_weights')  # 将保存好的权重信息加载的新的模型中"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "tensorflow_gpu",
   "language": "python",
   "name": "tensorflow_gpu"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
